import axios from 'axios';
import { ElMessage, ElLoading } from 'element-plus';
import type { LoadingInstance } from 'element-plus/lib/components/loading/src/loading';

const instance = axios.create({
    baseURL: import.meta.env.VITE_API_URL,
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json',
    },
});
let loadingInstance: LoadingInstance | null = null;


instance.interceptors.request.use(config => {
    const token = localStorage.getItem('token');
    if (token) {
        config.headers.Authorization = `Bearer ${token}`;
    }
    startLoading();
    return config;
}, error => {
    closeLoading();
    return Promise.reject(error);
});

instance.interceptors.response.use(
    response => {
        closeLoading();
        return response
    },
    error => {
        closeLoading();
        const { response } = error;
        if (response) {
            handleResponseError(response.status);
        } else {
            ElMessage.error("网络异常，请检查您的网络连接。");
        }

        return Promise.reject(error);
    }
);

const handleResponseError = (status: number) => {
    switch (status) {
        case 401:
            localStorage.removeItem('token');
            ElMessage.warning("您的登录状态已过期，请重新登录。");
            break;
        case 403:
            ElMessage.error("您没有权限访问该资源。");
            break;
        case 500:
            ElMessage.error("服务器发生错误，请稍后再试。");
            break;
        default:
            console.error("未知错误:", status);
            ElMessage.error(`发生错误: ${status}`);
    }
}

const startLoading = () => {
    if (!loadingInstance) {
        loadingInstance = ElLoading.service({
            lock: true,
            text: '加载中...',
            background: 'rgba(0, 0, 0, 0.7)',
        });
    }
}
const closeLoading = () => {
    if (loadingInstance) {
        loadingInstance.close();
        loadingInstance = null;
    }
}

export default instance;